package vip.wangwenhao.autoconfigure.oauth2;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.web.filter.OncePerRequestFilter;
import vip.wangwenhao.autoconfigure.utils.Oauth2Utils;
import vip.wangwenhao.common.enums.ResultCode;
import vip.wangwenhao.common.result.Result;
import vip.wangwenhao.common.util.HttpUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RemoteTokenServices tokenServices;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String token = Oauth2Utils.getToken(request);
            if (StringUtils.isNotBlank(token)) {
                OAuth2Authentication oAuth2Authentication = tokenServices.loadAuthentication(token);
                if (null != oAuth2Authentication) {
                    SecurityContextHolder.getContext().setAuthentication(oAuth2Authentication);
                } else {
                    HttpUtils.response(response, HttpStatus.SC_OK, Result.fail(ResultCode.INVALID_TOKEN));
                    return;
                }
            }
        } catch (AuthenticationException e) {
            HttpUtils.response(response, HttpStatus.SC_OK, Result.fail(ResultCode.AUTHORIZATION_INVALID));
            return;
        } catch (InvalidTokenException e) {
            HttpUtils.response(response, HttpStatus.SC_OK, Result.fail(ResultCode.INVALID_TOKEN));
            return;
        }
        filterChain.doFilter(request, response);
    }
}